package com.alone.mybatisplus.demo.handler;

import cn.hutool.core.lang.Pair;
import cn.hutool.core.util.RandomUtil;
import com.alone.mybatisplus.datascope.core.loader.DataScopeHandler;
import com.alone.mybatisplus.demo.entity.DeptMapper;
import com.alone.mybatisplus.datascope.conts.DataScopeModel;
import com.alone.mybatisplus.datascope.conts.DataScopeType;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @author Alone
 * @date 2022/5/13 1:49 下午
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class UserHandler extends DataScopeHandler {

    private final DeptMapper deptMapper;

    @Override
    public boolean canHandle(DataScopeModel model) {
        return DataScopeModel.USER == model;
    }

    @Override
    public boolean allowAll(Long userId, DataScopeModel model) {
        return false;
    }

    @Override
    protected void setInValue(Long userId, DataScopeModel model, List<Pair<String, Set<?>>> inValue) {
        // 加载当前用户数据全新啊具体类型
        List<Integer> dataScopeTypes = loadCurrentUserDataScopeTypes();
        log.info("当前随机的数据权限为: {}", dataScopeTypes);
        Long dept = loadCurrentUserDept();
        log.info("当前随机的用户部门为: {}", dept);
        log.info("当前随机的用户为: {}", userId);

        // 支持去重
        for (Integer dataScopeType : dataScopeTypes) {
            if (DataScopeType.USER_OWN_CHILD_LEVEL.getValue().equals(dataScopeType)) {
                inValue.add(Pair.of("dept_id", Collections.singleton(dept)));
            } else if (DataScopeType.USER_OWN_LEVEL.getValue().equals(dataScopeType)) {
                Set<Long> deptIds = deptMapper.recursiveFindByPid(dept);
                deptIds.add(dept);
                inValue.add(Pair.of("dept_id", deptIds));
            } else if (DataScopeType.USER_OWN.getValue().equals(dataScopeType)) {
                inValue.add(Pair.of("id", Collections.singleton(userId)));
            }
        }
    }

    private List<Integer> loadCurrentUserDataScopeTypes() {
        int randomInt1 = RandomUtil.randomInt(DataScopeType.USER_OWN_CHILD_LEVEL.getValue(), DataScopeType.USER_OWN.getValue() + 1);
        int randomInt2 = RandomUtil.randomInt(DataScopeType.USER_OWN_CHILD_LEVEL.getValue(), DataScopeType.USER_OWN.getValue() + 1);
        return Arrays.asList(randomInt1, randomInt2);
    }

    private Long loadCurrentUserDept() {
        return RandomUtil.randomLong(1L, 5L);
    }
}
